<?php
namespace system\libraries\database;

use system\core\Config;
use system\core\Exception;

/**
 * Database Adapter
 * 
 * @author Steffen Brem <steffenbrem@gmail.com>
 * @package System.Libraries.Database
 */
class Adapter 
{
    /**
     * Stores all the Database settings
     * 
     * @var array
     */    
    private $_config;
    
    /**
     * Stores the current Database group
     * 
     * @var string
     */
    private $_group;
    
    /**
     * Stores the PDO instance
     * 
     * @var PDO
     */
    private $_connection;
    
    /**
     * Stores the Adapter instance
     * 
     * @var system\libraries\database\Adapter
     */
    private static $_instance;
    
    /**
     * Constructor
     */
    private function __construct( $group = NULL )
    {
        $this->_config = Config::get('database');
 
        $active = Config::get('database', 'active');

        if ( $group )
        {
            if ( key_exists($group, $this->_config) )
            {
                $this->_group = $group;
            }
            else
            {
                throw new \Exception('The database group "' . $group . '" does not exist.', 300);
            }
        }
        else
        {
            if ( key_exists($active, $this->_config) )
            {
                $this->_group = $active;
            }
            else
            {
                throw new \Exception('There is no "default" database group in your database config.');
            }
        }

        $this->_connect($group);
    }
    
    /**
     * Get the PDO instance
     * 
     * @param string $group
     * @return \PDO
     */
    public static function getInstance( $group = NULL )
    {
        if ( ! self::$_instance instanceof Adapter )
        {
            self::$_instance = new Adapter( $group );
        }
        
        return self::$_instance;
    }
    
    public function getConnection()
    {
        return $this->_connection;
    }
    
    /**
     * Connect to the Database
     * 
     * @param string $group
     * @return \PDO 
     */
    private function _connect( $group = NULL )
    {
        $dsn = $this->_config[$this->_group]['engine'] . ':host=' . $this->_config[$this->_group]['hostname'] . ';dbname=' . $this->_config[$this->_group]['database'];
        
        $pdo = new \PDO($dsn, $this->_config[$this->_group]['username'], $this->_config[$this->_group]['password']);
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        $this->_connection = $pdo;
    }
}

/* End of file Adapter.php */